<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box{
            position: absolute;
            width: 100px;
            height: 100px;
            background-color: skyblue;
        }
        .span{
            position: absolute;
            width: 1px;
            height: 1000px;
            background-color: black;
            left: 1000px;
            top: 0px;
        }
    </style>
    <script>
        window.onload = function(){
            var btn = document.getElementById("btn");
            var box = document.getElementsByClassName("box")[0];
            var bt = document.getElementById("bt");
            var siv;
            var left = 0;
            
            // obj为要移动的物体，speed为移动速度
            // target为移动的终点，action为移动的方向
            function move (obj, speed, target, action){
                // 开启定时器前先关闭上一个定时器
                clearInterval(obj.siv);
                var object = getComputedStyle(obj, null);
                // 获取obj当前位置
                var location = parseInt(object[action]);
                    if (location > target){
                        speed = -speed;
                    }
                // 设置定时器
                obj.siv = setInterval(function(){
                    object = getComputedStyle(obj, null);
                    var oldValue = parseInt(object[action]);
                    var newValue = oldValue+speed;
                    if (newValue >= target && speed > 0 || newValue <= target && speed < 0){
                        newValue = target;
                    }
                    // 修改obj的位置
                    obj.style[action] = newValue+"px";
                    // 设置obj的移动终点
                    if (newValue == target){
                        clearInterval(obj.siv);
                    }
                },50);
            }

            // 给bt绑定单击相应函数
            bt.onclick = function(){
                move (box,19,900,"left");
            }
            btn.onclick = function(){
                move (box,19,0,"left");
            }
        }
    </script>
</head>
<body>
    <button id="btn">左移</button>
    <button id="bt">右移</button>
    <div class="box"></div>
    <div class="span"></div>
</body>
</html>